import 'dart:async';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:bluetooth_print_plus/bluetooth_print_plus.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wallpaper/components/button/normal_button.dart';

class Bluetooth extends StatefulWidget {
  const Bluetooth({super.key});

  @override
  State<Bluetooth> createState() => _BluetoothState();
}

class _BluetoothState extends State<Bluetooth> {
  BluetoothDevice? _device;
  late StreamSubscription<bool> _isScanningSubscription;
  late StreamSubscription<BlueState> _blueStateSubscription;
  late StreamSubscription<ConnectState> _connectStateSubscription;
  late StreamSubscription<Uint8List> _receivedDataSubscription;
  late StreamSubscription<List<BluetoothDevice>> _scanResultsSubscription;
  List<BluetoothDevice> _scanResults = [];
  String successAddress = '';
  TscCommand tscCommand = TscCommand();

  void write() async {
    final ByteData bytes = await rootBundle.load("assets/dithered-image.png");

    /// 打印图片:
    final Uint8List image = bytes.buffer.asUint8List();
    await tscCommand.cleanCommand();
    await tscCommand.size(width: 76, height: 130);
    await tscCommand.cls(); // most after size
    await tscCommand.image(image: image, x: 50, y: 60);
    await tscCommand.print(1);
    final cmd = await tscCommand.getCommand();
    if (cmd == null) return;
    BluetoothPrintPlus.write(cmd);
  }

  @override
  void initState() {
    super.initState();
    initBluetoothPrintPlusListen();
  }

  @override
  void dispose() {
    super.dispose();
    _isScanningSubscription.cancel();
    _blueStateSubscription.cancel();
    _connectStateSubscription.cancel();
    _receivedDataSubscription.cancel();
    _scanResultsSubscription.cancel();
    _scanResults.clear();
  }

  Future<void> initBluetoothPrintPlusListen() async {
    /// 监听扫描结果
    _scanResultsSubscription = BluetoothPrintPlus.scanResults.listen((event) {
      if (mounted) {
        setState(() {
          _scanResults = event;
        });
      }
    });

    /// 监听是否正在扫描
    _isScanningSubscription = BluetoothPrintPlus.isScanning.listen((event) {
      print('监听是否正在扫描: $event ');
      if (mounted) {
        setState(() {});
      }
    });

    /// 监听蓝牙状态变化
    _blueStateSubscription = BluetoothPrintPlus.blueState.listen((event) {
      print('监听蓝牙状态变化: $event');
      if (mounted) {
        setState(() {});
      }
    });

    /// 监听连接状态变化
    _connectStateSubscription = BluetoothPrintPlus.connectState.listen((event) {
      print('监听连接状态变化: $event ');
      switch (event) {
        case ConnectState.connected:
          setState(() {
            if (_device == null) return;
            // 连接成功后可以跳转到其他页面或者执行打印任务
          });
          break;
        case ConnectState.disconnected:
          setState(() {
            _device = null;
          });
          break;
      }
    });

    /// 监听接收到的数据
    _receivedDataSubscription = BluetoothPrintPlus.receivedData.listen((data) {
      print('监听接收到的数据: $data ');

      /// 处理接收到的数据
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              SizedBox(
                width: 100,
                child: NormalButton(
                  title: '停止',
                  height: 30,
                  fontSize: 16,
                  radius: 5,
                  onPressed: onStopPressed,
                  bgColor: Colors.red,
                ),
              ),
              SizedBox(
                width: 100,
                child: NormalButton(
                  title: '扫描',
                  onPressed: onScanPressed,
                  radius: 5,
                  height: 30,
                  fontSize: 16,
                ),
              )
            ],
          ),
          Expanded(
              child: SafeArea(
            child: BluetoothPrintPlus.isBlueOn
                ? ListView(
                    children: [
                      for (var device in _scanResults)
                        Padding(
                          padding: const EdgeInsets.all(4.0),
                          child: Material(
                            color:
                                Theme.of(context).colorScheme.primaryContainer,
                            borderRadius: BorderRadius.circular(10),
                            child: ListTile(
                              title: Text('名称：${device.name}'),
                              subtitle: Text('地址：${device.address}'),
                              leading: Icon(Icons.bluetooth),
                              trailing: successAddress == device.address
                                  ? Icon(Icons.check_sharp, color: Colors.green)
                                  : null,
                              onTap: () async {
                                var res =
                                    await BluetoothPrintPlus.connect(device);
                                if (res != null) {
                                  // 模拟连接成功
                                  successAddress = device.address;
                                  BotToast.showText(text: '连接成功');
                                } else {
                                  BotToast.showText(text: '连接失败');
                                }
                              },
                            ),
                          ),
                        )
                    ],
                  )
                : buildBlueOffWidget(),
          )),
        ],
      ),
    );
  }

  Widget buildBlueOffWidget() {
    return Center(
      child: Text(
        "Bluetooth is turned off\nPlease turn on Bluetooth...",
        style: TextStyle(
            fontWeight: FontWeight.w700, fontSize: 16, color: Colors.red),
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget buildScanButton(BuildContext context) {
    if (BluetoothPrintPlus.isScanningNow) {
      return FloatingActionButton(
        onPressed: onStopPressed,
        backgroundColor: Colors.red,
        child: Icon(Icons.stop),
      );
    } else {
      return FloatingActionButton(
        onPressed: onScanPressed,
        backgroundColor: Colors.green,
        child: Text("SCAN"),
      );
    }
  }

  Future onScanPressed() async {
    if (!BluetoothPrintPlus.isBlueOn) {
      BotToast.showText(text: '请先打开蓝牙');
    }
    // 检查蓝牙权限和位置权限是否已授予
    // 检查权限状态
    final status = await Permission.locationWhenInUse.status;
    print('=========================================================');
    print(status.isGranted);
    // 处理未授权情况
    if (!status.isGranted) {
      final result = await Permission.locationWhenInUse.request();
      if (!result.isGranted) {
        BotToast.showText(text: '需要位置权限发现蓝牙设备');
        return;
      }
    }

    try {
      await BluetoothPrintPlus.startScan(timeout: Duration(seconds: 10));
    } catch (e) {
      print("onScanPressed error: $e");
    }
  }

  Future onStopPressed() async {
    try {
      BluetoothPrintPlus.stopScan();
    } catch (e) {
      print("onStopPressed error: $e");
    }
  }
}
